<template>
  <!-- 近1月访客量变化 -->
  <div class="visitor-change chart-box1">
    <div class="chart-title">近1月访客量变化</div>
    <div class="chart-content" :id="chartId"></div>
  </div>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  nextTick,
  onBeforeUnmount,
  toRaw,
  watch,
} from "vue";
import { Chart, registerTheme } from "@antv/g2";
import common from "../../utils/common";
import store from "../../../../store";

export default defineComponent({
  name: "VisitorChange  ",
  setup(props) {
    const state = reactive({
      chart: null,
      chartId: "visitorChangeChart",
      data: [],
    });

    const initChart = () => {
      const data = state.data;
      state.chart = new Chart({
        container: state.chartId,
        autoFit: true,
        theme: "chartTheme",
      });
      state.chart.data(data);

      state.chart.scale("value", {
        nice: true,
        alias: "访客量（人）",
      });

      state.chart.axis("value", {
        label: {
          formatter: (text) => {
            return text.replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
          },
        },
      });

      state.chart.line().position("time*value");
      state.chart.area().position("time*value");
      state.chart.render();
    };

    watch(
      () => store.getters.flow.VisitorNumberChange,
      (val) => {
        if (val) {
          getData();
        }
      }
    );

    const getData = () => {
      const { VisitorNumberChange } = store.getters.flow;
      if (VisitorNumberChange) {
        state.data = VisitorNumberChange;
      }
      if (state.chart) {
        state.chart.changeData(toRaw(state.data));
      } else {
        nextTick(() => {
          initChart();
        });
      }
    };

    onMounted(() => {
      registerTheme("chartTheme", common.chartTheme);
      getData();
    });

    onBeforeUnmount(() => {
      const chartBox = document.getElementById(state.chartId);
      if (chartBox) {
        chartBox.innerHTML = "";
      }
    });

    return {
      ...toRefs(state),
    };
  },
});
</script>

<style lang="less" scoped>
@import "../../styles/common.less";
</style>
